

package funcs

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/toolkits/nux"
	"log"
	"time"
)

type Network struct {
	NetworkName    string `json:"network_name"`  //网卡名
	InBytes        int64  `json:"in_bytes"`		 //上传总字节数
	InPackages     int64  `json:"in_packages"`   //上传总包数
	OutBytes       int64  `json:"out_bytes"`	 //下载总字节数
	OutPackages    int64  `json:"out_packages"`  //下载总包数
	TotalBytes     int64  `json:"total_bytes"`   //总字节数
	TotalPackages  int64  `json:"total_packages"`//总包数
}

// 网卡名 一般来说Linux网卡都是这三种
var ifacePrefix = []string{"eth", "em", "ens"}

// 网速采集，使用当前和前一秒的接受字节数之差就是当前网速单位KB/S 参数是网卡名
func NetworkSpeed(networkName string) (upload float64, download float64) {
	oldNetIfs, err := nux.NetIfs(ifacePrefix)
	if err != nil {
		log.Println(err)
		logrus.Error("Get Network Info field")
		return
	}
	time.Sleep(time.Second * 1)
	newNetIfs, err := nux.NetIfs(ifacePrefix)
	if err != nil {
		log.Println(err)
		logrus.Error("Get Network Info field")
		return
	}
	fmt.Printf("newNetIfs = %v\n",newNetIfs)
        fmt.Printf("oldNetIfs = %v\n",oldNetIfs)
	var oldNet *nux.NetIf
	var newNet *nux.NetIf
	for index, data:= range oldNetIfs{
		if data.Iface == networkName {
			oldNet = oldNetIfs[index]
			break
		}
	}
	for index, data:= range newNetIfs{
		if data.Iface == networkName {
			newNet = newNetIfs[index]
			break
		}
	}
	if oldNet == nil || newNet == nil{
		logrus.Error("NetworkName Error!")
		fmt.Println("NetworkName Error!")
		return 0,0
	}

	return float64((newNet.InBytes - oldNet.InBytes))/1024 , float64((newNet.OutBytes - oldNet.OutBytes))/1024
}

// 获取主机所有网卡名称
func NetworkNameList() []string  {
	netIfs, err := nux.NetIfs(ifacePrefix)
	if err != nil {
		log.Println(err)
		logrus.Error("Get Network Info field")
		return nil
	}
	var results []string
	for _, data := range netIfs {
		results = append(results, data.Iface)
	}
	return results
}
// 根据网卡获取网络信息
func NetWorkInfo(networkName string) *Network  {

	netIfs, err := nux.NetIfs(ifacePrefix)
	if err != nil {
		log.Println(err)
		logrus.Error("Get Network Info field")
		return nil
	}
	network := Network{}

	for _, data:= range netIfs{
		if data.Iface == networkName {
			network.NetworkName = data.Iface
			network.InBytes = data.InBytes
			network.OutBytes = data.OutBytes
			network.InPackages = data.InPackages
			network.OutPackages = data.OutPackages
			network.TotalBytes = data.TotalBytes
			network.TotalPackages = data.TotalPackages
			break
		}
	}

	return &network
}
